package org.example.rabbitmq.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.rabbitmq.bean.Book;
import org.example.rabbitmq.config.MyAMQPConfig;
import org.example.rabbitmq.service.BookService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@RestController
@RequestMapping("/test")
public class AmqpController {

    private static final Logger logger = LoggerFactory.getLogger(AmqpController.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private BookService bookService;

    @Autowired
    private ObjectMapper objectMapper;  // 用于 JSON 序列化/反序列化

    @GetMapping("/send")
    public String sendMsg() {
        for (int i = 0; i < 10; i++) {   // 发送10次消息
            Book book = new Book(null, "Java程序设计", "Java教研室");
            rabbitTemplate.convertAndSend(MyAMQPConfig.TEST_EXCHANGE_NAME, MyAMQPConfig.TEST_ROUTING_KEY, book);
            logger.info("生产者发送第{}条消息: {}", i, book);
        }

        return "发送成功";
    }

    @GetMapping("/receive")
    public void receive() {
        Message message;
        while ((message = rabbitTemplate.receive(MyAMQPConfig.TEST_QUEUE_NAME)) != null) {
            try {
                // 将消息体转换为字符串
                String messageBody = new String(message.getBody());

                // 将字符串转换为 Book 对象
                Book book = objectMapper.readValue(messageBody, Book.class);

                // 保存 Book 对象到数据库
                bookService.saveBook(book);

                logger.info("消费者接收消息并保存到数据库: {}", book);
            } catch (IOException e) {
                logger.error("消息解析失败: {}", e.getMessage(), e);
            } catch (Exception e) {
                logger.error("处理消息时发生错误: {}", e.getMessage(), e);
            }
        }
        logger.info("没有更多消息");
    }
}